今天來實作遊戲角色
VTuber角色可以在遊戲場景中上下左右移動。
玩家可以透過鍵盤操作VTuber角色。
首先,建立player.rs並引入必要的模組:
use bevy::prelude::*;
創建一個Player
結構,代表遊戲中的玩家:
struct Player;
接著,定義玩家移動的邏輯:
fn player_movement(
keyboard_input: Res<Input<KeyCode>>,
mut query: Query<(&Player, &mut Transform)>
) {
for (_player, mut transform) in query.iter_mut() {
const MOVEMENT_SPEED: f32 = 4.0;
if keyboard_input.pressed(KeyCode::W) {
transform.translation.y += MOVEMENT_SPEED;
}
if keyboard_input.pressed(KeyCode::S) {
transform.translation.y -= MOVEMENT_SPEED;
}
if keyboard_input.pressed(KeyCode::A) {
transform.translation.x -= MOVEMENT_SPEED;
}
if keyboard_input.pressed(KeyCode::D) {
transform.translation.x += MOVEMENT_SPEED;
}
}
}
遊戲場景中將隨機生成敵人。
敵人會根據某種算法追蹤玩家。
首先,創建一個Enemy結構:
struct Enemy;
接著,定義敵人的移動邏輯:
fn enemy_movement(
mut query: Query<(&Enemy, &mut Transform)>,
player_query: Query<(&Player, &Transform)>
) {
if let Some((_player, player_transform)) = player_query.iter().next() {
for (_enemy, mut enemy_transform) in query.iter_mut() {
const ENEMY_SPEED: f32 = 2.0;
let direction = (player_transform.translation - enemy_transform.translation).normalize();
enemy_transform.translation += direction * ENEMY_SPEED;
}
}
}